<script setup>
// 详情页面
import {useRoute, useRouter} from "vue-router";
import {onMounted, reactive, ref, onBeforeMount} from "vue";
import {HTTP} from "@/api/HTTP.js";
import {ElMessage} from 'element-plus'
import {onBeforeRouteLeave} from "vue-router";
import useTimeStore from '@/stores/ReadTime/index.js'
import axios from "axios";

const route = useRoute()
const router = useRouter()
// 商品详情数据
const DetailData = ref([])
// 评论数据
const CommentData = ref([])
const dialogVisible = ref(false)
const useTime = useTimeStore()
//  路由守卫
useTime.recordEnterTime()
onBeforeRouteLeave((to, from, next) => {
  useTime.recordLeaveTime()
  console.log('用户进入详情页的时间', useTime.leaveTime - useTime.enterTime, 'ms')// 计算时间差
  next()
})
// 获取商品详情和评论数据
// 在组件挂载时获取数据
onBeforeMount(async () => {
  await getCommentData()
});

// 获取评论数据
const getCommentData = async () => {
  try {
    const [response1, response2] = await Promise.all([
      HTTP.get(`/item/detail?product_id=${route.params.id}`),
      HTTP.get(`/comment?product_id=${route.params.id}`)
    ]);

    DetailData.value = response1.data;
    CommentData.value = response2.data;
    console.log(CommentData.value)
  } catch (error) {
    console.error('商品详情或评论数据获取失败:', error);
  }
}
// 返回上一页
const handleBack = () => {
  router.go(-1)
}

// 选择配置
const SelectValue = ref('请选择配置')
const SelectData = ref(0)
const handleSelect = (value) => {
  SelectData.value = value
  console.log(value)
}
const handleNow = async () => {
  let formData = new FormData()
  formData.append('type_id', SelectData.value)
  try {
    if (SelectData.value === 0) {
      ElMessage({
        message: '请选择配置',
        type: 'error',
      })
      return
    }
    await HTTP.post('/item/immed', formData).then(response => {
      console.log(response)
      if (response.code === 10200) {
        ElMessage({
          message: '立即购买成功',
          type: 'success',
        });
      } else {
        ElMessage({
          message: '立即购买失败',
          type: 'error',
        });
      }
    })
  } catch (error) {
    ElMessage({
      message: '加入订单失败',
      type: 'error',
    })
  }
}

// 加入购物车
const handleJoinCart = async () => {
  let formData = new FormData()
  if (SelectData.value === 0) {
    ElMessage({
      message: '请选择配置',
      type: 'error',
    })
    return
  }
  formData.append('type_id', SelectData.value)
  try {
    const response = await HTTP.post('/item', formData);
    console.log(response);

    if (response.code === 10200) {
      ElMessage({
        message: '加入购物车成功',
        type: 'success',
      });
    } else {
      ElMessage({
        message: '加入购物车失败',
        type: 'error',
      });
    }
  } catch (error) {
    console.error('Error adding to cart:', error);
    ElMessage({
      message: '加入购物车时发生错误',
      type: 'error',
    });
  } finally {
    dialogVisible.value = false;
  }
};

// 显示写评论弹窗
const ShowComment = ref(false)
const form = ref({
  comment: '',
  productId: Number(route.params.id),
  score: 0
})
// 写评论功能
const handleWriting = () => {
  ShowComment.value = true
}

// 修改评论内容
let config = {
  method: 'post',
  url: 'http://localhost:8080/comment',
  data: form.value,
  headers: {
    'Content-Type': 'application/json',
    'token': localStorage.getItem('token')
  }
}
const handleComment = async () => {
  try {
    if (!form.value.comment) {
      ElMessage({
        message: '评论内容不能为空',
        type: 'error',
      });
      return
    }

    if (form.value.comment.length < 10) {
      ElMessage({
        message: '评论内容不能少于10个字',
        type: 'error',
      });
      return
    }

    if (form.value.comment.length > 50) {
      ElMessage({
        message: '评论内容不能高于50个字',
        type: 'error',
      });
      return
    }

    if (form.value.score === 0) {
      ElMessage({
        message: '给个评分吧',
        type: 'error',
      });
      return
    }
    const response = await axios(config)
    console.log(response);
    if (response.data.code === 50000) {
      ElMessage({
        message: '评论成功',
        type: 'success',
      });
      ShowComment.value = false
    } else {
      ElMessage({
        message: '评论失败',
        type: 'error',
      });
    }
  } catch (error) {
    console.error('Error writing comment:', error);
    ElMessage({
      message: '评论时发生错误',
      type: 'error',
    });
  } finally {
    await getCommentData()
  }
}

const value = ref(4)
</script>

<template>
  <div class="detail">
    <h1>
      <i class="iconfont icon-fanhui4"
         @click="handleBack"
      ></i>
    </h1>
    <div class="flex justify-center">
      <div class="detail_main">
        <!-- 购物-->
        <div class="detail_shopping">
          <div class="detail_left">
            <img :src="DetailData.img" alt="">
            <div class="detail_info">
              <p>商品名称:
                <span>
                {{ DetailData.name }}
              </span>
              </p>
              <p>商品价格:
                <span>
                {{ DetailData.price + '元' }}
              </span>
              </p>
              <div v-if="DetailData.types && DetailData.types[0] && DetailData.types[0].length > 0">
                <p>商品配置:</p>
                <el-select
                    v-model="SelectValue"
                    size="default"
                    @change="handleSelect"
                    placeholder="请选择配置"
                    style="width: 240px"
                >
                  <el-option
                      v-for="item in DetailData.types[0]"
                      :key="item.typeId"
                      :label="item.typeName"
                      :value="item.typeId"
                  />
                </el-select>
              </div>
            </div>
          </div>
          <div class="detail_right">
            <!-- 加入购物车的弹框-->
            <el-dialog
                v-model="dialogVisible"
                width="500">
              <span>你确定加入购物车吗？</span>
              <template #footer>
                <div class="dialog-footer">
                  <el-button @click="dialogVisible = false">返回</el-button>
                  <el-button type="primary" @click="handleJoinCart()">
                    确定
                  </el-button>
                </div>
              </template>
            </el-dialog>
            <el-button type="danger" @click="handleNow">立即购买</el-button>
            <el-button type="warning" @click="dialogVisible = true">加入购物车</el-button>
          </div>
        </div>
        <!-- 商品信息-->
        <div class="card detail_content" style="width: 1200px">
          <div class="card-body">
            <h5 class="card-title">商品信息</h5>
            <h6 class="card-subtitle mb-2 text-muted">{{ DetailData.description }}</h6>
          </div>
        </div>
        <!--商品评论-->
        <div class="card detail_comment" style="width: 1200px;">
          <div class="card-body">
            <div class="title_comment">
              <h5 class="card-title">商品评论</h5>
              <el-button round @click="handleWriting">写评论</el-button>
            </div>
            <div class="card_comment">
              <el-empty v-if="CommentData.list.length === 0"
                        description="这里还没有人评论喵~"/>
              <div class="father_comment" v-for="item in CommentData.list" :key="item">
                <div class="flex_comment">
                  <el-avatar
                      :size="50"
                      src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"
                  />
                  <p>{{ item.username }}</p>
                  <div style="width: 300px;">
                    <span style="font-size: 14px">TA的评分：</span>
                    <span><el-rate v-model="value" size="large"/></span>
                  </div>
                </div>
                <p>{{ item.comment }}</p>
                <el-divider border-style="dashed"/>
              </div>

              <!-- 消息弹出框-->
              <el-dialog v-model="ShowComment" title="写点什么吧" width="800">
                <el-form :model="form">
                  <el-form-item label-width="10px">
                    <el-input v-model="form.comment" :autosize="{ minRows: 7, maxRows: 10 }" placeholder="请输入内容"
                              type="textarea"/>
                  </el-form-item>
                  <el-form-item label="给个评分吧" label-width="100px">
                    <el-rate v-model="form.score" size="large"/>
                  </el-form-item>
                </el-form>
                <template #footer>
                  <div class="dialog-footer">
                    <el-button @click="ShowComment = false">返回</el-button>
                    <el-button type="primary" @click="handleComment">
                      提交
                    </el-button>
                  </div>
                </template>
              </el-dialog>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.detail {
  width: 1535px;
  margin: 0 auto;
  height: 100vh;
  overflow: hidden;
  background: #ffdada;

  h1 {
    margin-left: 30px;

    i {
      cursor: pointer;
      font-size: 40px;
      font-weight: bold;
    }
  }

  .detail_main {
    width: 1200px;
    height: 100vh;
    overflow-x: hidden;
    overflow-y: scroll;

    .detail_shopping {
      width: 1200px;
      height: 210px;
      display: flex;
      justify-content: space-between;

      .detail_left {
        width: 800px;
        height: 210px;
        display: flex;

        img {
          width: 160px;
          height: 210px;
          background-color: white;
        }

        .detail_info {
          margin-left: 40px;

          p {
            font-size: 24px;
            font-weight: bold;
            margin-top: 10px;

            span {
              font-family: 宋体, serif;
            }
          }
        }
      }

      .detail_right {

        .el-button {
          margin-top: 10px;
          width: 130px;
          height: 40px;
          font-size: 18px;
        }
      }
    }

    .detail_content {
      height: auto;
      margin-top: 20px;
    }

    .detail_comment {
      margin-top: 20px;
      height: 510px;
      overflow-x: hidden;
      overflow-y: scroll;


      .title_comment {
        display: flex;
        width: 100%;
        height: 50px;
        justify-content: space-between;
        justify-items: center;

        .el-button {
          width: 100px;
          font-size: 18px;
          height: 40px;
          margin-right: 10px;
        }
      }

      .card_comment {
        .father_comment {
          width: 100%;
          height: auto;

          .flex_comment {
            display: flex;
            margin: 20px;
            justify-content: start;
            justify-items: center;

            p {
              width: 100%;
              height: 50px;
              margin-left: 10px;
              color: #df8c8c;
              line-height: 50px;
              font-size: 20px;
            }
          }

          p {
            font-size: 20px;
            margin: 0 25px;
          }
        }
      }
    }
  }
}
</style>